package com.coffee_shop_app

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import com.coffee_shop_app.module.http.MyNanoHttpService
import com.coffee_shop_app.module.http.MyNanoHttpdServer
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
import java.net.Inet4Address
import java.net.NetworkInterface
import java.net.SocketException


class MainActivity : ReactActivity() {
  /**
   * Returns the name of the main component registered from JavaScript. This is used to schedule
   * rendering of the component.
   */
  override fun getMainComponentName(): String = "coffee_shop_app"

  /**
   * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
   * which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
   */
  override fun createReactActivityDelegate(): ReactActivityDelegate =
      DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    checkPermission();
    //实例化 获取ip 地址
    MyNanoHttpdServer.getInstance("127.0.0.1",this)
   //启动服务监听
    startService(Intent(this, MyNanoHttpService::class.java))

  }

  // DON'T FORGET to stop the server
  /**
   * 停止服务
   */
  override fun onDestroy() {
    super.onDestroy();
    if (MyNanoHttpdServer.getInstance("127.0.0.1", this) != null) MyNanoHttpdServer.getInstance("127.0.0.1", this).stop()
  }
  /**
   * 获得IP地址，分为两种情况:
   * 一：是wifi下；
   * 二：是移动网络下；
   */
  fun getIPAddress(): String? {
    val context: Context = this;
    val info = (context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
    if (info != null && info.isConnected) {
      if (info.type == ConnectivityManager.TYPE_MOBILE) { //当前使用2G/3G/4G网络
        try {
          //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
          val en = NetworkInterface.getNetworkInterfaces()
          while (en.hasMoreElements()) {
            val intf = en.nextElement()
            val enumIpAddr = intf.inetAddresses
            while (enumIpAddr.hasMoreElements()) {
              val inetAddress = enumIpAddr.nextElement()
              if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                return inetAddress.getHostAddress()
              }
            }
          }
        } catch (e: SocketException) {
          e.printStackTrace()
        }
      } else if (info.type == ConnectivityManager.TYPE_WIFI) { //当前使用无线网络
        val wifiManager = context.getSystemService(WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManager.connectionInfo
        //调用方法将int转换为地址字符串
        return intIP2StringIP(wifiInfo.ipAddress)
      }
    } else {
      //当前无网络连接,请在设置中打开网络
    }
    return null
  }

  /**
   * 将得到的int类型的IP转换为String类型
   * @param ip
   * @return
   */
  fun intIP2StringIP(ip: Int): String {
    return (ip and 0xFF).toString() + "." +
            (ip shr 8 and 0xFF) + "." +
            (ip shr 16 and 0xFF) + "." +
            (ip shr 24 and 0xFF)
  }

  /**
   * 检查存储权限
   */
  fun checkPermission(): Boolean? {
    var isGranted = true
    if (Build.VERSION.SDK_INT >= 23) {
      if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        isGranted = false
      }
      if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        isGranted = false
      }
      //            Log.i("aaaaa"," : "+isGranted);
      if (!isGranted) {
        this.requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE),
                102)

      }
    }
    return isGranted
  }
}
